<template>
  <div class="app-container" ref="refMainForm">
    <div class="my-define-dialog-title">
      {{reqForm.dialogTitle}}
      <div class="my-define-dialog-title-btn">
        <i @click="triggerComment" class="saas-iconfont saas-icon-xiaoxi" v-bind:class="{'is-active':showComment}"></i>
        <!-- <i v-if="!reqForm.denyEdit" @click="submitForm" class="saas-iconfont saas-icon-baocun1"></i> -->
        <i @click="cancel(false)" class="saas-iconfont saas-icon-caozuo-quanping-shousuo"></i>
      </div>
    </div>
    <el-scrollbar :style="customeStyle" class="my-form-scrollbar">
      <el-row class="my-dialog-top-row">
        <el-col class="my-left-col" :span="rowCol" style="height: 100%;">
          <el-form size="medium" ref="myForm" :model="reqForm.formData" :label-width="labelForm.labelWidth"
            :label-position="labelForm.labelPosition">
            <el-row v-if="reqForm.formData!=null">
              <el-col v-if="item.id>0" :span="24" v-for="(item,index) in fieldData" :key="index">
                <!-- 文本框 -->
                <el-form-item v-if="item.fieldType==1" :prop="item.field" :rules="{
                      required: item.fieldRequired, message: '请输入', trigger: 'change'}">
                  <template slot="label">
                    {{item.label}}
                    <el-link @click="doChooseRoom()" type="primary" class="choose-link"
                      v-if="item.field=='RepairLocation'&&!reqForm.denyEdit">
                      选择资源
                    </el-link>
                  </template>
                  <el-input :disabled="checkFormDisable(item)" v-model="reqForm.formData[item.field]"
                    placeholder="请输入" />
                </el-form-item>
                <!-- 数字框 -->
                <el-form-item v-if="item.fieldType==9" :prop="item.field" :rules="{
                      required: item.fieldRequired, message: '请输入', trigger: 'change'}">
                  <template slot="label">
                    {{item.label}}
                  </template>
                  <el-input type="number" style="text-align: right;" :disabled="checkFormDisable(item)"
                    v-model="reqForm.formData[item.field]" placeholder="请输入" />
                </el-form-item>
                <!-- 日期时间框 -->
                <el-form-item v-if="item.fieldType==2" :label="item.label" :prop="item.field" :rules="{
                      required: item.fieldRequired, message: '请选择', trigger: 'change'}">
                  <el-date-picker :disabled="checkFormDisable(item)" style="width: 100%;"
                    value-format="yyyy-MM-dd HH:mm:ss" v-model="reqForm.formData[item.field]" type="datetime"
                    placeholder="请选择">
                  </el-date-picker>
                </el-form-item>
                <!-- 日期框 -->
                <el-form-item v-if="item.fieldType==8" :label="item.label" :prop="item.field" :rules="{
                      required: item.fieldRequired, message: '请选择', trigger: 'change'}">
                  <el-date-picker :disabled="checkFormDisable(item)" style="width: 100%;"
                    value-format="yyyy-MM-dd HH:mm:ss" v-model="reqForm.formData[item.field]" type="date"
                    placeholder="请选择">
                  </el-date-picker>
                </el-form-item>
                <!-- 下拉选择（单选） -->
                <el-form-item v-if="item.fieldType==3" :prop="item.field" :rules="{
                      required: item.fieldRequired, message: '请选择', trigger: 'change'}">
                  <template slot="label">
                    {{item.label}}
                  </template>
                  <el-select :disabled="checkFormDisable(item)" style="width: 100%;"
                    @change="(val)=>handleChangeSelect(val,item)" v-model="reqForm.formData[item.field]"
                    placeholder="请选择">
                    <el-option v-for="(item,index) in item.fieldData" :key="index" :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <!-- 下拉选择（多选） -->
                <el-form-item v-if="item.fieldType==4" :label="item.label" :prop="item.field" :rules="{
                      required: item.fieldRequired, message: '请选择', trigger: 'change'}">
                  <el-select :disabled="checkFormDisable(item)" style="width: 100%;" multiple
                    v-model="reqForm.formData[item.field]" placeholder="请选择">
                    <el-option v-for="(item2,index2) in item.fieldData" :key="index2" :label="item2.label"
                      :value="item2.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <!-- 单选框 -->
                <el-form-item v-if="item.fieldType==5" :label="item.label" :prop="item.field" :rules="{
                      required: item.fieldRequired, message: '请选择', trigger: 'change'}">
                  <el-radio-group :disabled="checkFormDisable(item)" v-model="reqForm.formData[item.field]">
                    <el-radio v-for="(item2,index2) in item.fieldData" :key="index2" :label="item2.value">
                      {{item2.label}}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="item.fieldType==6" :label="item.label" :prop="item.field" :rules="{
                      required: item.fieldRequired, message: '请输入', trigger: 'change'}">
                  <el-input type="textarea" :rows="5" v-model="reqForm.formData[item.field]" placeholder="请输入" />
                </el-form-item>
                <!-- 下拉树（单选） -->
                <el-form-item v-if="item.fieldType==7" :label="item.label" :prop="item.field" :rules="{
                      required: item.fieldRequired, message: '请选择', trigger: 'change'}">
                  <el-cascader style="width: 100%;" :disabled="checkFormDisable(item)"
                    v-model="reqForm.formData[item.field]" :options="item.fieldData"
                    :props="{checkStrictly: true,value:'Id',label:'Name'}" clearable>
                  </el-cascader>
                </el-form-item>
                <!-- 附件 -->
                <el-form-item v-if="item.fieldType==11" label="附件" :prop="item.field" :rules="{
                  required: item.fieldRequired,
                  message: '请选择附件',
                  trigger: 'change'
                }">
                  <!-- <el-upload :action="uploadAction" name="saasyyFile" :headers="uploadHeaders"
                        :on-remove="handleFileRemove" :on-success="handleFileSuccess" :file-list="reqForm.uploadFormData.fileList"
                        :data="uploadData">
                        <el-button v-if="!reqForm.denyEdit" size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip"></div>
                      </el-upload> -->
                  <el-upload :disabled="reqForm.denyEdit" :action="uploadAction" name="saasyyFile"
                    :headers="uploadHeaders" :on-remove="(file, fileList)=>handleFileRemove(file, fileList, item)"
                    :on-success="(res, file)=>handleFileSuccess(res, file,item)"
                    :file-list="reqForm.formData['fileList_' + item.field]" :data="uploadData" :list-type="uploadListType"
                    :on-preview="handlePictureCardPreview">
                    <i v-if="uploadListType=='picture-card'" class="el-icon-plus"></i>
                    <el-button v-else size="small" type="primary">点击上传
                    </el-button>
                    <div slot="tip" class="el-upload__tip"></div>
                  </el-upload>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
        <el-col class="my-right-col" :span="10" v-if="showComment" style="height: 100%;">
          <div class="my-dontai-title">动态
            <span class="dongtai-btn">
              <el-dropdown @command="handleDongTaiCommand">
                <span class="el-dropdown-link">
                  {{dongTaiTitle}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="0">全部</el-dropdown-item>
                  <el-dropdown-item command="2">仅评论</el-dropdown-item>
                  <el-dropdown-item command="3">仅提醒</el-dropdown-item>
                  <el-dropdown-item command="1">仅修改历史</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </span>
          </div>
          <el-empty v-if="reqForm.recordData.length==0&&logData.length==0">
            <span slot="description">
              当前没有动态
            </span>
          </el-empty>
          <el-timeline v-if="reqForm.recordData.length>0" class="my-el-timeline" style="padding: 20px 10px">
            <el-timeline-item v-for="(activity, index) in reqForm.recordData" :key="index" :timestamp="activity.remark">
              <div class="my-el-timeline-item-title">
                {{activity.title}}
                <label class="my-el-timeline-item-time">
                  {{activity.time}}
                </label>
              </div>
            </el-timeline-item>
          </el-timeline>
          <div v-if="logData.length>0">
            <div class="my-define-message-item" v-for="(item,index) in logData" :key="index">
              <div class="my-define-message-date">
                {{item.date}} {{item.time}} <span style="margin-left: 20px;">{{item.name}}{{item.summary}}</span>
                <div class="my-define-message-btn" v-if="!reqForm.denyEdit">
                  <svg-icon @click="doReplyComment(item)" v-if="item.typeId==2" class="my-icon-comment"
                    icon-class="icon-comment" />
                  <svg-icon @click="doRemoveComment(item)" v-if="item.typeId!=1" class="my-icon-remove"
                    icon-class="icon-remove" />
                </div>
              </div>
              <!-- <div class="my-define-message-time-user">
                {{item.time}}
                {{item.name}}
              </div>
              <div class="my-define-message-summary">
                {{item.summary}}
              </div> -->
              <div class="my-define-message-value" v-if="item.typeId==1">
                <span v-if="item.fromValue" class="my-define-message-value1"> {{item.fromValue}}</span>
                <span class="my-define-message-value2"> {{item.toValue}}</span>
              </div>
              <div class="my-define-message-comment" v-if="item.typeId==2">
                <div v-if="item.fromValue" class="my-define-message-comment1"> {{item.fromValue}}</div>
                <div class="my-define-message-comment2">{{item.toValue}}</div>
              </div>
              <div class="my-define-message-remind" v-if="item.typeId==3">
                <div class="my-define-message-remind-item">时间
                  <el-date-picker :disabled="reqForm.denyEdit" @change="(val)=>submitSaveRemind(val,item)" size="mini"
                    style="width: 120px;" value-format="yyyy-MM-dd" v-model="item.remindDate" type="date"
                    placeholder="请选择">
                  </el-date-picker>
                  <el-time-select :disabled="reqForm.denyEdit" @change="(val)=>submitSaveRemind(val,item)" size="mini"
                    style="width: 100px;" v-model="item.remindTime" :picker-options="{
                      start: '08:30',
                      step: '00:15',
                      end: '18:30'
                    }" placeholder="选择时间">
                  </el-time-select>
                </div>
                <div class="my-define-message-remind-item">提醒
                  <el-input :disabled="reqForm.denyEdit" @change="(val)=>submitSaveRemind(val,item)"
                    style="width: 225px" size="mini" v-model="item.remark" placeholder="请输入"></el-input>
                </div>
                <div class="my-define-message-remind-item">人员
                  <el-select :disabled="reqForm.denyEdit" @change="(val)=>submitSaveRemind(val,item)" size="mini"
                    style="width: 225px;" v-model="item.remindUserIdList" multiple filterable placeholder="请选择">
                    <el-option v-for="item2 in remindUserList" :key="item2.value" :label="item2.label"
                      :value="item2.value">
                    </el-option>
                  </el-select>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-scrollbar>
    <div class="comment-bottom-reply" v-if="showCommentReply">
      <el-input type="textarea" :rows="5" style="margin-top: 20px;" placeholder="请输入" v-model="commentValue"
        :maxlength="50" show-word-limit>
      </el-input>
      <el-button @click="submitComment" class="reply-send-btn" size="mini" type="primary">发送</el-button>
    </div>
    <div @click="doCloseMask" class="my-form-mask-bg" v-if="showMaskBg"></div>
    <el-dialog custom-class="my-common-dialog" :width="dialogWidth" :close-on-click-modal="false"
      :visible.sync="showDetail" :show-close="false" append-to-body>
      <div :is="currentView" v-if="showDetail" :dialogTitle="showTitle"></div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import {
    getToken
  } from '@/utils/auth'
  import {
    getFormField,
    saveRowComment,
    removeComment,
    saveColumnRemind,
  } from '@/api/system/column'
  import {
    getOperationLog
  } from '@/api/system/system'
  import defaultSettings from '@/settings'
  export default {
    name: 'master-form',
    components: {
      roomChoose
    },
    props: {
      reqForm: {
        type: Object,
        default: () => ({
          formData: {},
          dialogTitle: '',
          uploadFormData: {
            required: false,
            uploadFile: false,
            uploadFolder: 'Service',
            fileList: [],
            listType: 'picture-card'
          },
          denyEdit: false,
          recordData: []
        })
      },
      sceneType: {
        type: Number,
        default: 0
      },
      sceneId: {
        type: Number,
        default: 0
      },
      defineSceneId: {
        type: Number,
        default: 0
      }
    },
    data() {
      return {
        customeStyle: {
          height: (window.innerHeight - 180) + 'px'
        },
        labelForm: defaultSettings.labelForm,
        fieldData: [],
        form: {
          Id: 0
        },
        uploadHeaders: {
          profile: getToken()
        },
        uploadData: {
          FolderName: this.reqForm.uploadFormData.uploadFolder
        },
        uploadAction: process.env.VUE_APP_BASE_API + '/Common/Upload/UploadFile',
        showComment: true,
        rowCol: 14,
        dialogWidth: '50%',
        showDetail: false,
        currentView: '',
        showTitle: '',
        uploadListType: '',
        dialogImageUrl: '',
        dialogVisible: false,
        logData: [],
        remindUserList: [],
        commentValue: '',
        showCommentReply: false,
        currentLog: null,
        dongTaiTitle: '全部',
        dongTaiType: 0
      }
    },
    computed: {
      showMaskBg() {
        return this.showCommentReply
      }
    },
    created() {
      this.getData()
      if (!this.reqForm.formData.Id) {
        this.triggerComment()
      }
      this.uploadListType = this.reqForm.uploadFormData.listType || ''
    },
    methods: {
      addClickEvent() {
        document.addEventListener('click', this.handleClickEvent, false)
      },
      removeClickEvent() {
        document.removeEventListener('click', this.handleClickEvent, false)
      },
      handleClickEvent(e) {
        e.preventDefault()
        if (e.target.nodeName == 'BODY') {
          return
        }
        if (!this.$refs.refMainForm.contains(e.target)) {
          console.log(e.target)
          this.submitForm()
          // this.removeClickEvent()
        }
      },
      /** 查询列表 */
      getData() {
        getFormField({
          sceneType: this.sceneType,
          sceneId: this.sceneId,
          defineSceneId: this.defineSceneId
        }).then(res => {
          if (res.status) {
            this.fieldData = res.outputData
          }
          this.getLog()
        })
      },
      handleFileRemove(file, fileList, item) {
        var fileList = this.reqForm.formData['fileList_' + item.field]
        var index = fileList.findIndex(item => {
          return item.uid === file.uid;
        });
        if (index >= 0) {
          fileList.splice(index, 1);
        }
        var fileIdList = []
        fileList.forEach(function(fileItem) {
          fileIdList.push(fileItem.fileId)
        })
        this.reqForm.formData['fileList_' + item.field] = fileList
        this.reqForm.formData[item.field] = fileIdList.join(',')
      },
      handleFileSuccess(res, file, item) {
        if (res.status) {
          var fileList = this.reqForm.formData['fileList_' + item.field]
          fileList.push({
            fileId: res.outputData.fileId,
            name: file.name,
            url: res.outputData.fileUrl,
            uid: file.uid
          })
          var fileIdList = []
          fileList.forEach(function(fileItem) {
            fileIdList.push(fileItem.fileId)
          })
          this.reqForm.formData['fileList_' + item.field] = fileList
          this.reqForm.formData[item.field] = fileIdList.join(',')
        }
      },
      submitForm() {
        var that = this;
        if (this.reqForm.denyEdit) {
          this.cancel()
          return
        }
        this.$refs['myForm'].validate(valid => {
          if (valid) {
            var dataList = [];
            that.fieldData.forEach(function(item) {
              item.fieldValue = that.reqForm.formData[item.field]
              if (typeof item.fieldValue == 'object') {
                item.fieldValue = JSON.stringify(item.fieldValue)
              }
              if (item.fieldValue == 'null') {
                item.fieldValue = null
              }
              if (item.fieldValue == '[]') {
                item.fieldValue = ''
              }
              dataList.push({
                id: item.id,
                defineId: item.defineId,
                field: item.field,
                fieldValue: item.fieldValue,
                fieldType: item.fieldType
              })
            })
            var fileIdList = []
            this.reqForm.uploadFormData.fileList.forEach(function(fileItem) {
              fileIdList.push(fileItem.fileId)
            })
            var fileIds = fileIdList.join(',')
            this.$$parent(this, "submitForm", dataList, fileIds)
          } else {
            this.cancel()
          }
        })
      },
      cancel(reload) {
        this.$$parent(this, "doClosePop", reload)
      },
      triggerComment() {
        this.showComment = !this.showComment
        if (this.showComment) {
          this.rowCol = 14
        } else {
          this.rowCol = 24
        }
      },
      handleChangeSelect(val, item) {
        item.fieldData.forEach((item2) => {
          if (item2.value == this.reqForm.formData[item.field]) {
            item.fieldLabel = item2.label
          }
        })
      },
      checkFormDisable(item) {
        if (this.reqForm.denyEdit) {
          return true
        }
        if (item.field == 'RepairLocation') {
          if (this.reqForm.formData['ServiceAreaType'] == 1) {
            return true
          }
        }
      },
      doChooseRoom() {
        this.showDetail = true
        this.showTitle = '选择资源'
        this.currentView = 'roomChoose'
      },
      doClosePop(reload) {
        this.showDetail = false
      },
      doSaveRoomChoose(data) {
        var item1 = this.fieldData.filter((item) => {
          return item.field == 'RepairLocation'
        })
        if (item1.length > 0) {
          this.reqForm.formData['RepairLocation'] = data[0].label
          var item2 = this.fieldData.filter((item) => {
            return item.field == 'RelateRoomId'
          })
          var fieldValue = this.reqForm.formData['ServiceAreaType'] == 1 ? data[0].value : 0
          if (item2.length > 0) {
            item2[0].fieldValue = data[0].value
          } else {
            this.fieldData.push({
              field: "RelateRoomId",
              fieldRequired: true,
              fieldType: 1,
              fieldValue: fieldValue,
              id: 0,
              label: "所属资源"
            })
          }
          this.reqForm.formData['RelateRoomId'] = fieldValue
        }
        this.showDetail = false
      },
      handlePictureCardPreview(file) {
        window.open(file.url)
        // this.dialogImageUrl = file.url;
        // this.dialogVisible = true;
      },
      getLog() {
        getOperationLog({
          sceneType: this.sceneType,
          Id: this.reqForm.formData.Id,
          dType: this.dongTaiType,
          sceneId: this.sceneId,
          defineSceneId: this.defineSceneId
        }).then(res => {
          if (res.status) {
            this.logData = res.outputData.logList
            this.remindUserList = res.outputData.userList
          }
        })
      },
      doCloseMask() {
        this.currentLog = null
        this.showCommentReply = false
        this.commentValue = ''
      },
      doReplyComment(item) {
        this.currentLog = item
        this.showCommentReply = true
        this.commentValue = ''
      },
      submitComment() {
        if (!this.commentValue) {
          return
        }
        saveRowComment({
          sceneType: this.sceneType,
          sceneId: this.sceneId,
          defineSceneId: this.defineSceneId,
          rowId: this.reqForm.formData.Id,
          content: this.commentValue,
          parentId: this.currentLog.relateId
        }).then(res => {
          if (res.status) {
            this.doCloseMask()
            this.getLog()
            setTimeout(() => {
              this.$$parent(this, "reloadList")
            }, 200)
          }
        })
      },
      doRemoveComment(item) {
        removeComment({
          Id: item.id
        }).then(res => {
          if (res.status) {
            this.getLog()
            setTimeout(() => {
              this.$$parent(this, "reloadList")
            }, 200)
          }
        })
      },
      submitSaveRemind(val, item) {
        var that = this;
        var postForm = {
          sceneType: this.sceneType,
          defineSceneId: this.defineSceneId,
          rowId: this.reqForm.formData.Id,
          Id: item.relateId,
          dateValue: item.remindDate,
          timeValue: item.remindTime,
          remindOn: true,
          remark: item.remark,
          remarkOn: true,
          userIds: JSON.stringify(item.remindUserIdList)
        }
        saveColumnRemind(postForm).then(res => {
          if (res.status) {
            this.$message({
              message: '提交成功',
              type: 'success'
            })
            this.$$parent(this, "reloadList")
          }
        })
      },
      handleDongTaiCommand(command) {
        this.dongTaiType = command
        if (command == 0) {
          this.dongTaiTitle = '全部'
        }
        if (command == 2) {
          this.dongTaiTitle = '仅评论'
        }
        if (command == 3) {
          this.dongTaiTitle = '仅提醒'
        }
        if (command == 1) {
          this.dongTaiTitle = '仅修改历史'
        }
        this.getLog()
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss">
  .my-dontai-title {
    font-size: 14px;
    line-height: 40px;
    border-bottom: solid 0.5px #d1d1d1;
    padding-left: 16px;
    color: #262626;
    font-weight: 700;
    position: relative;
	border-image: linear-gradient( to bottom,transparent  50%,#ddd 50%) 0 0 100% 0 ;

    .dongtai-btn {
      position: absolute;
      right: 10px;

      .el-dropdown-link {
        font-size: 14px;
      }
    }
  }

  .my-el-timeline .el-timeline-item__timestamp.is-bottom {
    line-height: 25px;
  }

  .my-el-timeline-item-title {
    font-weight: bold;
  }

  label.my-el-timeline-item-time {
    font-weight: normal;
    display: inline-block;
    margin-left: 20px;
  }

  .el-link.choose-link {
    font-size: 14px;
    margin-left: 10px;
  }

  .my-form-scrollbar.el-scrollbar .el-scrollbar__view {
    height: 100%;

    .my-dialog-top-row.el-row {
      height: 100%;

      .my-left-col {
        background-color: #fff;
      }

      .my-right-col {}
    }

    .my-define-message-comment {
      background-color: #fff;
      border-radius: 5px;
      padding: 5px 10px;

      .my-define-message-comment1 {
        background-color: #f8f8f8;
        padding: 5px 10px;
        border-radius: 5px;
        margin-bottom: 10px;
      }
    }

    .my-define-message-remind {
      .el-input--suffix .el-input__inner {
        padding-right: 10px;
      }

      .my-define-message-remind-item {
        margin-top: 10px;
      }
    }

    .my-define-message-btn {
      position: absolute;
      top: 0;
      right: 5px;

      .my-icon-comment {
        width: 20px;
        height: 20px;
        vertical-align: -5px;
        cursor: pointer;
        margin-right: 5px;
      }

      .my-icon-remove {
        width: 15px;
        height: 15px;
        vertical-align: -2px;
        cursor: pointer;
      }
    }
  }

  .comment-bottom-reply {
    position: absolute;
    bottom: 0;
    left: 50%;
    right: 0;
    height: 150px;
    background: reba(0, 0, 0, 0);
    z-index: 2000;

    .reply-send-btn {
      position: absolute;
      right: 10px;
      bottom: 20px;
    }
  }

  .my-form-mask-bg {
    background: rgba(0, 0, 0, 0);
    z-index: 1999;
    position: absolute;
    top: 0;
    bottom: 0;
    width: 100%;
  }
</style>
